import time
from db import read_data, save_data
from interface import check_login, login_user_dict
from interface import show_product, count_product_price, renew_product_interface, get_product_name, add_shop_cart
from conf.settings import get_logger


def check_product(func):
    def inner(*args, **kwargs):
        flag_data, reading_data = read_data(tag='product', path=f'product_data.json')
        if not flag_data:
            return reading_data
        else:
            return func(*args, **kwargs)

    return inner


# 购物功能
@check_product
def show_all_product():
    show_product()
    return '商品展示完毕'


@check_product
def settlement_product():
    login_user = login_user_dict["username"]
    flag_data, reading_data = read_data(tag='info', path=f'{login_user}_info.json')
    if not flag_data:
        return reading_data
    flag, product_dict = get_product_name()
    if not flag:
        return product_dict
    flag, balance_product = count_product_price(product=product_dict['name'])
    if not flag:
        return balance_product
    if reading_data[login_user]['balance'] < balance_product:
        return f"用户金额不足,当前余额{reading_data[login_user]['balance']}"
    reading_data[login_user]['balance'] = login_user_dict['balance'] - balance_product
    save_data(tag='info', path=f"{login_user}_info.json", data=reading_data)
    flag, msg = renew_product_interface(product=product_dict['name'])
    if not flag:
        return msg
    else:
        msg = f"{login_user} 结算商品 {product_dict['name']} 成功 共消费 {balance_product} 元"
        product_logger = get_logger(tag='product', username='product')
        product_logger.info(msg)
        user_logger = get_logger(tag='user', username=login_user)
        user_logger.info(msg)
        return msg


@check_product
def add_shopping_cart():
    login_user = login_user_dict["username"]
    flag, shopping_cart = add_shop_cart()
    if not flag:
        return shopping_cart
    user_logger = get_logger(tag='user', username=login_user)
    for k, v in shopping_cart.items():
        msg = f"{login_user} 添加 {v} 件 {k} 至购物车 "
        user_logger.info(msg)
        print(msg)
    flag_data, reading_data = read_data(tag='info', path=f'{login_user}_info.json')
    if not flag_data:
        return reading_data
    reading_data[login_user]['shop_cart'].update(shopping_cart)
    flag, msg = save_data(tag='info', path=f"{login_user}_info.json", data=reading_data)
    if not flag:
        return msg
    return '添加购物车成功'


def settlement_shopping_cart():
    login_user = login_user_dict["username"]
    flag_data, reading_data = read_data(tag='info', path=f'{login_user}_info.json')
    if not flag_data:
        return reading_data
    shopping_cart = reading_data[login_user]["shop_cart"]
    if not shopping_cart:
        return "当前购物车为空！"
    print(f"当前登录用户{login_user} 的购物车如下:")
    gross_balance = 0
    for k, v in shopping_cart.items():
        msg = f"  商品名称: {k}  |   商品数量 {v} 件 "
        print(msg)
        flag, balance = count_product_price(product=k, count=v)
        if not flag:
            return balance
        gross_balance += balance
    print(f"购物车共计金额 {gross_balance} 元")
    settle_choice = input("请输入是否确认结算：是(y) / 否 (其他) :")
    if settle_choice != 'y':
        return "已退出结算购物出！"
    if reading_data[login_user]['balance'] < gross_balance:
        return f"当前登录用户余额不足! 当前余额{reading_data[login_user]['balance']} 元 !"
    reading_data[login_user]['balance'] = login_user_dict['balance'] - gross_balance
    reading_data[login_user]['shop_cart'] = {}
    save_data(tag='info', path=f"{login_user}_info.json", data=reading_data)
    for k, v in shopping_cart.items():
        flag, msg = renew_product_interface(product=k, count=v)
        if not flag:
            return msg
    log = f"{login_user} 结算购物车成功,共消费{gross_balance}元,购物车内容概览{shopping_cart}"
    user_logger = get_logger(tag='user', username=login_user)
    user_logger.info(log)
    product_logger = get_logger(tag='product', username='product')
    product_logger.info(log)
    return log


def check_shopping_cart():
    login_user = login_user_dict["username"]
    flag_data, reading_data = read_data(tag='info', path=f'{login_user}_info.json')
    if not flag_data:
        return reading_data
    shopping_cart = reading_data[login_user]["shop_cart"]
    print(f"当前登录用户{login_user} 的购物车如下:")
    for k, v in shopping_cart.items():
        msg = f"  商品名称: {k}  |   商品数量 {v} 件 "
        print(msg)
    user_logger = get_logger(tag='user', username=login_user)
    user_logger.info(f"{login_user} 查看购物车成功")
    return '查看购物车结束'


def modify_shopping_cart():
    login_user = login_user_dict["username"]
    flag_data, reading_data = read_data(tag='info', path=f'{login_user}_info.json')
    if not flag_data:
        return reading_data
    print("将清空您的购物车，并重新输入！")
    flag, shopping_cart = add_shop_cart()
    if not flag:
        return shopping_cart
    reading_data[login_user]['shop_cart'] = shopping_cart
    flag, msg = save_data(tag='info', path=f"{login_user}_info.json", data=reading_data)
    if not flag:
        return msg
    print(f"当前登录用户{login_user} 的购物车如下:")
    for k, v in shopping_cart.items():
        msg = f"  商品名称: {k}  |   商品数量 {v} 件 "
        print(msg)
    user_logger = get_logger(tag='user', username=login_user)
    for k, v in shopping_cart.items():
        msg = f"修改 : {login_user} 添加 {v} 件 {k} 至购物车 "
        user_logger.info(msg)
    return '修改购物车成功'


def quit_system():
    return 'break'


func_menu = '''
===================== Shopping =====================
1.商品展示       2.商品结算(单个商品结算)     3.添加购物车        
4.结算购物车      5.查看购物车               6.修改购物车
7.退出购物系统
======================欢迎使用=======================
'''

Shopping_func_dict = {
    1: show_all_product,
    2: settlement_product,
    3: add_shopping_cart,
    4: settlement_shopping_cart,
    5: check_shopping_cart,
    6: modify_shopping_cart,
    7: quit_system,
}


@check_login
def shopping_main():
    while True:
        print(func_menu)
        choice_func = input("请输入功能ID:>>>").strip()
        choice_func = int(choice_func)
        func = Shopping_func_dict[choice_func]
        msg = func()
        if msg == 'break':
            time.sleep(0.5)
            break
        print(msg)
    return "购物系统已退出"
